package com.tsinghuabigdata.edu.ddmath.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;

import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tsinghuabigdata.edu.ddmath.MVPModel.MyStudyModel;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.MainActivity;
import com.tsinghuabigdata.edu.ddmath.adapter.SubmitedAgencyWorkAdatper;
import com.tsinghuabigdata.edu.ddmath.adapter.ToSubmitAgencyWorkAdatper;
import com.tsinghuabigdata.edu.ddmath.bean.DoudouWork;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.MonthSumbitedItem;
import com.tsinghuabigdata.edu.ddmath.bean.SubmitQuestion;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.DDUploadActivity;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.DDWorkManager;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.WorkCommitListener;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.DataUtils;
import com.tsinghuabigdata.edu.ddmath.view.LoadingPager;
import com.tsinghuabigdata.edu.ddmath.view.MultiGridView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;


/**
 * 机构作业
 * Created by Administrator on 2017/3/14.
 */

public class AgencyWorkFragment extends Fragment implements View.OnClickListener, WorkCommitListener {

    private static final String TAG = "AgencyWorkFragment";

    private static final int ToSubmitWork = 0;
    private static final int SubmitedWork = 1;

    private PullToRefreshListView mLvDoudouWork;
    private LoadingPager          mLoadingPager;
    private View                  mViewTosubmit;
    private CheckBox              mCbMore;
    private MultiGridView         mGvToSubmit;

    private Context      mContext;
    private MainActivity mainActivity;
    private MyStudyModel mMyStudyModel = new MyStudyModel();

    private ToSubmitAgencyWorkAdatper mToSubmitAgencyWorkAdatper;
    private SubmitedAgencyWorkAdatper mSubmitedAgencyWorkAdatper;
    private int pageNum  = 1;
    private int pageSize = 20;
    private String accessToken;
    private String studentId;
    private String classId;
    private String mLoginName;

    private List<SubmitQuestion>      mListToSumbit = new ArrayList<SubmitQuestion>();
    private List<SubmitQuestion>      mListShow     = new ArrayList<SubmitQuestion>();
    private List<MonthSumbitedItem>   mListSumbited = new ArrayList<MonthSumbitedItem>();
    private HashMap<Integer, Boolean> mHashMap      = new HashMap<Integer, Boolean>();
    private DDWorkManager mDDWorkManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i("burning", "AgencyWorkFragment onCreateView");
        View root = inflater.inflate(R.layout.fragment_agency_work, container, false);
        initView(root);
        initData();
        return root;
    }

    private void initView(View root) {
        mContext = getActivity();
        mainActivity = (MainActivity) getActivity();
        mLvDoudouWork = (PullToRefreshListView) root.findViewById(R.id.lv_doudou_work);
        mLoadingPager = (LoadingPager) root.findViewById(R.id.loadingPager_doudou_work);
        ILoadingLayout loadingLayout = mLvDoudouWork.getLoadingLayoutProxy(true, false);
        loadingLayout.setRefreshingLabel("刷新中...");
        loadingLayout.setLoadingDrawable(getResources().getDrawable(R.drawable.refresh_loading_anim));

        mLoadingPager.setTargetView(mLvDoudouWork);
        mLoadingPager.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoadingPager.showLoading();
                queryToSubmitWork();
                querySubmitedWork();
            }
        });

        mViewTosubmit = getActivity().getLayoutInflater().inflate(R.layout.view_to_submit, null);
        mCbMore = (CheckBox) mViewTosubmit.findViewById(R.id.cb_to_submit_more);
        mGvToSubmit = (MultiGridView) mViewTosubmit.findViewById(R.id.gv_to_submit);
        mLvDoudouWork.getRefreshableView().addHeaderView(mViewTosubmit);
        mCbMore.setOnClickListener(this);
        mGvToSubmit.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SubmitQuestion submitQuestion = mListToSumbit.get(position);
                if (submitQuestion != null) {
                    Intent intent = new Intent(mContext, DDUploadActivity.class);
                    intent.putExtra(DDUploadActivity.PARAM_DDWORKID, submitQuestion.getExamId());
                    intent.putExtra(DDUploadActivity.PARAM_TITLE, submitQuestion.getExerName());
                    startActivity(intent);
                }
            }
        });
    }

    private void initData() {
        //        mSubmitedAgencyWorkAdatper = new SubmitedAgencyWorkAdatper(mContext, mListSumbited);
        //        mLvDoudouWork.setAdapter(mSubmitedAgencyWorkAdatper);
        createLoginInfo();
    }

    //查询登录信息
    private void createLoginInfo() {
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if (loginInfo != null) {
            accessToken = loginInfo.getAccessToken();
            mLoginName = loginInfo.getLoginName();
            Log.i(TAG, "accessToken=" + accessToken + "mLoginName=" + mLoginName);
            UserDetailinfo detailinfo = AccountUtils.getUserdetailInfo();
            if (detailinfo == null || detailinfo.getJoinedClassInfoList() == null || detailinfo.getJoinedClassInfoList().size() == 0) {

            } else {
                classId = detailinfo.getJoinedClassInfoList().get(0).getClassId();
                studentId = detailinfo.getStudentId();
                queryData();
                Log.i(TAG, "classId=" + classId + "studentId=" + studentId);
            }
        }
    }

    //查询机构作业列表
    public void queryData() {
        queryToSubmitWork();
        querySubmitedWork();
        setUploadListener();
    }

    //上传作业监听
    private void setUploadListener() {
        //// TODO: 2017/3/24 上传作业监听
        DDWorkManager.getDDWorkManager(mContext, mLoginName);
        mDDWorkManager = DDWorkManager.getDDWorkManager();
        if (mDDWorkManager != null) {
            mDDWorkManager.addCommitListener(this);
        }
    }

    //查询待提交机构作业列表
    private void queryToSubmitWork() {
        int status = 0;
        mMyStudyModel.queryDoudouWork(accessToken, studentId, pageNum, pageSize, status, new RequestListener<DoudouWork>() {

            @Override
            public void onSuccess(DoudouWork vo) {
                Log.i(TAG, "queryToSubmitWork onSuccess");
                if (vo == null) {
                    queryResult(ToSubmitWork, false);
                    return;
                }
                List<SubmitQuestion> exerhomes = vo.getExerhomes();
                if (exerhomes == null || exerhomes.size() == 0) {
                    queryResult(ToSubmitWork, false);
                    return;
                }
                mListToSumbit.clear();
                mListToSumbit.addAll(exerhomes);
                mListShow.clear();
                mListShow.addAll(mListToSumbit);
                if (mToSubmitAgencyWorkAdatper == null) {
                    mToSubmitAgencyWorkAdatper = new ToSubmitAgencyWorkAdatper(mContext, mListShow);
                    mGvToSubmit.setAdapter(mToSubmitAgencyWorkAdatper);
                } else {
                    mToSubmitAgencyWorkAdatper.notifyDataSetChanged();
                }
                queryResult(ToSubmitWork, true);
            }

            @Override
            public void onFail(HttpResponse<DoudouWork> response, Exception ex) {
                Log.i(TAG, "queryToSubmitWork onFail");
                queryResult(ToSubmitWork, false);
                //                mLoadingPager.showFault();
            }
        });
    }


    //查询已提交机构作业列表
    private void querySubmitedWork() {
        int status = 1;
        mMyStudyModel.queryDoudouWork(accessToken, studentId, pageNum, pageSize, status, new RequestListener<DoudouWork>() {

            @Override
            public void onSuccess(DoudouWork vo) {
                Log.i(TAG, "querySubmitedWork onSuccess");
                if (vo == null) {
                    queryResult(SubmitedWork, false);
                    return;
                }
                List<SubmitQuestion> exerhomes = vo.getExerhomes();
                if (exerhomes == null || exerhomes.size() == 0) {
                    queryResult(SubmitedWork, false);
                    return;
                }
                mListSumbited.clear();
                mListSumbited.addAll(DataUtils.selectDoudouWork(exerhomes));
                if (mSubmitedAgencyWorkAdatper == null) {
                    mSubmitedAgencyWorkAdatper = new SubmitedAgencyWorkAdatper(mContext, mListSumbited);
                    mLvDoudouWork.setAdapter(mSubmitedAgencyWorkAdatper);
                } else {
                    mSubmitedAgencyWorkAdatper.notifyDataSetChanged();
                }
                queryResult(SubmitedWork, true);
            }

            @Override
            public void onFail(HttpResponse<DoudouWork> response, Exception ex) {
                Log.i(TAG, "querySubmitedWork onFail");
                queryResult(SubmitedWork, false);
                //                mLoadingPager.showFault();
            }
        });
    }

    //查询待提交/已提交豆豆作业列表的结果
    private synchronized void queryResult(int index, boolean success) {
        mHashMap.put(index, success);
        if (mHashMap.keySet().size() == 2) {
            if (mHashMap.containsValue(false)) {
                mLoadingPager.showFault();
                mHashMap.clear();
            } else {
                //两次都请求成功才展示列表
                mLoadingPager.showTarget();
            }
        }
    }

    //豆豆作业本地模拟数据
   /* private void analogDoudouWork() {
        Random random = new Random();
        for (int i = 0; i < 7; i++) {
            SubmitQuestion submitQuestion = new SubmitQuestion();
            submitQuestion.setStatus(random.nextInt(3));
            submitQuestion.setPageCount(random.nextInt(20));
            int day = random.nextInt(9);
            if (i < 3) {
                submitQuestion.setStartTime("2017-04-0" + day);
                submitQuestion.setEndTime("2017-04-0" + day);
                submitQuestion.setExerName("三角函数提高训练\n冲刺最后500题");
            } else {
                submitQuestion.setStartTime("2017-03-0" + day);
                submitQuestion.setEndTime("2017-03-0" + day);
                submitQuestion.setExerName("三角函数提高训练" + i);
            }
            submitQuestion.setOverdue(random.nextBoolean());
            mListToSumbit.add(submitQuestion);
        }
        Log.i(TAG, "mListToSumbit.size()= "+mListToSumbit.size());
        mListShow.clear();
        mListShow.addAll(mListToSumbit.subList(0,4));
        mToSubmitAgencyWorkAdatper = new ToSubmitAgencyWorkAdatper(mContext, mListShow);
        mGvToSubmit.setAdapter(mToSubmitAgencyWorkAdatper);

        List<SubmitQuestion> exerhomes = new ArrayList<SubmitQuestion>();
        for (int i = 0; i < 20; i++) {
            SubmitQuestion submitQuestion = new SubmitQuestion();
            int day = random.nextInt(9);
            if (i < 4) {
                submitQuestion.setStartTime("2017-04-0" + day);
            } else if (i < 11) {
                submitQuestion.setStartTime("2017-03-0" + day);
            } else if (i < 17) {
                submitQuestion.setStartTime("2017-02-0" + day);
            } else {
                submitQuestion.setStartTime("2017-01-0" + day);
            }
            submitQuestion.setOverdue(random.nextBoolean());
            submitQuestion.setExerStatus(1 + random.nextInt(3));
            submitQuestion.setRightQuestionCount(random.nextInt(20));
            submitQuestion.setWrongQuestionCount(random.nextInt(20));
            exerhomes.add(submitQuestion);
        }
        List<MonthSumbitedItem> monthSumbitedItems = DataUtils.selectDoudouWork(exerhomes);
        mListSumbited.addAll(monthSumbitedItems);
        mSubmitedAgencyWorkAdatper = new SubmitedAgencyWorkAdatper(mContext, mListSumbited);
        mLvDoudouWork.setAdapter(mSubmitedAgencyWorkAdatper);
        mLoadingPager.showTarget();
    }*/


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cb_to_submit_more:
                if (mCbMore.isChecked()) {
                    mListShow.clear();
                    mListShow.addAll(mListToSumbit);
                    Log.i(TAG, "isChecked mListShow.size()= " + mListShow.size());
                    mToSubmitAgencyWorkAdatper.notifyDataSetChanged();
                } else {
                    mListShow.clear();
                    mListShow.addAll(mListToSumbit.subList(0, 4));
                    Log.i(TAG, "mListShow.size()= " + mListShow.size());
                    mToSubmitAgencyWorkAdatper.notifyDataSetChanged();
                }
                break;
        }
    }

    @Override
    public void workStatus(String examId, int status) {
        for (int i = 0; i < mListToSumbit.size(); i++) {
            SubmitQuestion submitQuestion = mListToSumbit.get(i);
            if (examId.equals(submitQuestion.getExamId())) {
                submitQuestion.setStatus(status);
                int page = mDDWorkManager.getHavePageImage(examId);
                submitQuestion.setTakedpageCount(page);
            }
        }
        mToSubmitAgencyWorkAdatper.notifyDataSetChanged();
    }

    @Override
    public void pageStatus(String examId, int status) {


    }

    @Override
    public void onSuccess(String examId, Boolean res) {

    }

    @Override
    public void onFail(String examId, Exception ex) {
    }

    public void setId(String accessToken, String classId, String studentId) {
        this.accessToken = accessToken;
        this.classId = classId;
        this.studentId = studentId;
    }

}
